package LinkedList;

//给你一个链表的头节点 head 和一个整数 val ，
//请你删除链表中所有满足 Node.val == val 的节点，并返回 新的头节点 。
class ListNode {
     int val;
     ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }

public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode pre = null;
        ListNode cur = head;
        if(head ==null){
            return null;
        }
        while (cur.val == val) {
           if(cur.next != null) {
               cur = cur.next;
               head = cur;
           }else {
               return null;
           }
        }
        if(cur.next != null) {
            pre = cur;
            cur = cur.next;
        }else {
            return head;
        }
        while(cur.next != null) {
            if(cur.val == val) {
                pre.next = cur.next;
                cur = cur.next;
            }else {
                pre = cur;
                cur = cur.next;
            }
        }
        if(cur.val == val) {
            pre.next = null;
        }
         return head;
    }
}
